package com.wlper.lib.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.nearshop.R;
import com.wlper.lib.uitls.ViewUtils;
import com.wlper.lib.view.adapter.SimpleAdapterWithMarker;

/**
 * 可横向扩展的二级列表
 * 
 * @author wanliang527
 * 
 */
public class HorizontalExpandableList extends LinearLayout {

    private final static String[] KEYWORDS = { "全部", "不限" };// 当二级列表出现这些关键词时，显示一级列表的标题；
    private boolean isKeyLimit = true;

    private final static int HORIZONTAL_DIVIDER_WIDTH = 0;// 两个ListView之间分割线的宽度
    private final static String K_ITEM_NAME = "name";
    private final static String K_ITEM_ICON = "icon";
    private final static String K_ITEM_FLAG = "flag";
    public final static int LIST1 = 0;
    public final static int LIST2 = 1;
    public final static int BOTH = 2;

    private Context mContext;
    private ListView mListView1, mListView2;// 两个列表对象
    private SimpleAdapterWithMarker mListAdapter1, mListAdapter2;// 两个列表的适配器
    private View mHoriDivider;// 中间的分割线
    private ExpandableListAdapter mAdapter;// 适配器
    private Object normalBg1, selectedBg1, normalBg2, selectedBg2;// 两个列表的子项背景

    private int layoutId1 = R.layout.wl_view_hori_expand_list_item1;
    private int layoutId2 = R.layout.wl_view_hori_expand_list_item2;

    // private int selectedPos1 = -1, selectedPos2 = -1;

    private List<Map<String, Object>> mList1_Data = new ArrayList<Map<String, Object>>();// 列表1的数据
    private List<Map<String, Object>> mList2_Data = new ArrayList<Map<String, Object>>();// 列表2的数据

    public HorizontalExpandableList(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public HorizontalExpandableList(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        mContext = context;
        this.setOrientation(HORIZONTAL);
        this.setLayoutParams(ViewUtils.MATCH_MATCH);
        mListView1 = createListView();
        this.addView(mListView1);
        ((LinearLayout.LayoutParams) mListView1.getLayoutParams()).weight = 1;
        mHoriDivider = new View(mContext);
        mHoriDivider.setLayoutParams(new LayoutParams(HORIZONTAL_DIVIDER_WIDTH,
                LayoutParams.MATCH_PARENT));
        this.addView(mHoriDivider);
        mListView2 = createListView();
        this.addView(mListView2);
        ((LinearLayout.LayoutParams) mListView2.getLayoutParams()).weight = 1;
    }

    private ListView createListView() {
        ListView listView = new ListView(mContext);
        listView.setLayoutParams(ViewUtils.WRAP_MATCH);
        return listView;
    }

    /**
     * 设置一级列表和二级列表的背景
     * 
     * @param whichList
     *            可选值为HorizontalExpandableList.List1,HorizontalExpandableList.
     *            List2,HorizontalExpandableList.BOTH
     * @param bg
     *            Drawable对象获这资源ID。{@link} ViewUtils.setViewBackground(View v,
     *            Object obj)
     * @return
     */
    public boolean setListViewBackground(int whichList, Object bg) {
        switch (whichList) {
            case LIST1:
                return ViewUtils.setViewBackground(mListView1, bg);

            case LIST2:
                return ViewUtils.setViewBackground(mListView2, bg);

            case BOTH:
                return (setListViewBackground(LIST1, bg) && setListViewBackground(
                        LIST2, bg));

            default:
                return false;
        }

    }

    /**
     * 设置两个ListView的分隔线
     * 
     * @param drawable
     */
    public void setHorizontalDivier(Drawable drawable) {
        if (drawable != null)
            mHoriDivider.setBackgroundDrawable(drawable);
    }

    /**
     * 设置两个ListView的分隔线
     * 
     * @param resId
     */
    public void setHorizontalDivier(int resId) {
        try {
            mHoriDivider.setBackgroundResource(resId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置是否对诸如“全部、不限”等关键词的处理，当二级列表遇到这些关键词时，将显示一级列表的标题; 默认为true
     * 
     * @param limit
     */
    public void setKeyLimit(boolean limit) {
        this.isKeyLimit = limit;
    }

    /**
     * 设置列表名的字体大小和字体颜色。必须在setAdapter之后调用
     * 
     * @param which
     * @param textSize
     * @param textColor
     */
    public void setTextStyle(int which, int textSize, int textColor) {
        switch (which) {
            case LIST1:
                if (mListAdapter1 != null) {
                    mListAdapter1.customText(R.id.txt_v_item_name, textSize,
                            textColor);
                }
                break;
            case LIST2:
                if (mListAdapter2 != null) {
                    mListAdapter2.customText(R.id.txt_v_item_name, textSize,
                            textColor);
                }
                break;

            case BOTH:
                setTextStyle(LIST1, textSize, textColor);
                setTextStyle(LIST2, textSize, textColor);
                break;
        }
    }

    private void resetListData(List<Map<String, Object>> oldData,
            List<Map<String, Object>> newData) {
        oldData.clear();
        oldData.addAll(newData);
    }

    private void initListAdapter(int which,
            SimpleAdapterWithMarker.OnItemViewClickListener itemClickListener) {
        List<Map<String, Object>> data = null;
        String[] from = null;
        int[] to = null;
        switch (which) {
            case LIST1:
                data = mList1_Data;
                from = new String[] { K_ITEM_NAME, K_ITEM_ICON, K_ITEM_FLAG };
                to = new int[] { R.id.txt_v_item_name, R.id.image_v_item_icon,
                        R.id.image_v_go_more };
                mListAdapter1 = new SimpleAdapterWithMarker(mContext, data,
                        layoutId1, from, to);
                mListAdapter1.setItemClickListener(itemClickListener);
                break;

            case LIST2:
                data = mList2_Data;
                from = new String[] { K_ITEM_NAME };
                to = new int[] { R.id.txt_v_item_name };
                mListAdapter2 = new SimpleAdapterWithMarker(mContext, data,
                        layoutId2, from, to);
                mListAdapter2.setItemClickListener(itemClickListener);
                break;
        }
    }

    private void setListAdapter(int which) {

        switch (which) {
            case LIST1:
                SimpleAdapterWithMarker.OnItemViewClickListener itemClickListener1 = new SimpleAdapterWithMarker.OnItemViewClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        // selectedPos1 = position;
                        List<Map<String, Object>> data = mAdapter
                                .getList2_Data(position);
                        resetListData(mList2_Data, data);
                        mListAdapter2.notifyDataSetChanged();
                        if (data.size() == 0 && itemSelectedListener != null) {
                            TextView textView = (TextView) view
                                    .findViewById(R.id.txt_v_item_name);
                            itemSelectedListener.onItemSelected(view, textView
                                    .getText().toString(), position, -1);
                        }
                    }
                };
                initListAdapter(which, itemClickListener1);
                mListView1.setAdapter(mListAdapter1);
                break;

            case LIST2:
                SimpleAdapterWithMarker.OnItemViewClickListener itemClickListener2 = new SimpleAdapterWithMarker.OnItemViewClickListener() {

                    @Override
                    public void onItemClick(View view, int position) {
                        if (itemSelectedListener != null) {
                            String itemName = ((TextView) view
                                    .findViewById(R.id.txt_v_item_name))
                                    .getText().toString();
                            if (isKeyLimit) {
                                for (int i = 0; i < KEYWORDS.length; i++) {
                                    if (itemName.equals(KEYWORDS[i])) {
                                        int pos1 = mListAdapter1
                                                .getSelectedPos();
                                        itemName = (String) mList1_Data.get(
                                                pos1).get(K_ITEM_NAME);
                                    }
                                }
                            }
                            int pos1 = mListAdapter1.getSelectedPos();
                            itemSelectedListener.onItemSelected(view, itemName,
                                    pos1, position);
                        }
                    }
                };
                initListAdapter(which, itemClickListener2);
                mListView2.setAdapter(mListAdapter2);
                break;

            case BOTH:
                setListAdapter(LIST1);
                setListAdapter(LIST2);
                break;
        }

    }

    /**
     * 设置数据适配器
     * 
     * @param adapter
     *            {@link}ExpandableListAdapter
     */
    public void setAdapter(ExpandableListAdapter adapter) {
        mAdapter = adapter;
        if (mListView1.getAdapter() == null) {
            resetListData(mList1_Data, adapter.getList1_Data());
            setListAdapter(LIST1);
        } else {
            resetListData(mList1_Data, adapter.getList1_Data());
            mListAdapter1.notifyDataSetChanged();
        }
        if (mListView2.getAdapter() == null) {
            resetListData(mList2_Data, adapter.getList2_Data(0));
            setListAdapter(LIST2);
        } else {
            resetListData(mList2_Data,
                    adapter.getList2_Data(mListAdapter2.getSelectedPos()));
            mListAdapter2.notifyDataSetChanged();
        }
        setItemBackground(LIST1, normalBg1, selectedBg1);
        setItemBackground(LIST2, normalBg2, selectedBg2);
    }

    public ExpandableListAdapter getAdapter() {
        return mAdapter;
    }

    /**
     * 设置列表项的背景图。
     * 
     * @param which
     *            可选值为HorizontalExpandableList.List1,HorizontalExpandableList.
     *            List2,HorizontalExpandableList.BOTH
     * @param normalBg
     * @param selectedBg
     */
    public void setItemBackground(int which, Object normalBg, Object selectedBg) {
        if (which == LIST1) {
            if (mListAdapter1 == null) {
                normalBg1 = normalBg;
                selectedBg1 = selectedBg;
            } else {
                mListAdapter1.setItemBackground(normalBg, selectedBg);
            }
        } else if (which == LIST2) {
            if (mListAdapter2 == null) {
                normalBg2 = normalBg;
                selectedBg2 = selectedBg;
            } else {
                mListAdapter2.setItemBackground(normalBg, selectedBg);
            }
        } else if (which == BOTH) {
            setItemBackground(LIST1, normalBg, selectedBg);
            setItemBackground(LIST2, normalBg, selectedBg);
        }
    }

    /**
     * 获取列表对象
     * 
     * @param which
     *            可选值为HorizontalExpandableList.List1,HorizontalExpandableList.
     *            List2
     * @return
     */
    public ListView getListView(int which) {
        switch (which) {
            case LIST1:
                return mListView1;

            case LIST2:
                return mListView2;

            default:
                return null;
        }
    }

    private OnItemSelectedListener itemSelectedListener;

    /**
     * 设置列表项的点击事件
     * 
     * @param listener
     */
    public void setOnItemSelectedListener(OnItemSelectedListener listener) {
        this.itemSelectedListener = listener;
    }

    public interface OnItemSelectedListener {
        public void onItemSelected(View itemView, String itemName,
                int itemPos1, int itemPos2);
    }

    public static class ExpandableListAdapter {
        private List<String> mItemNames;
        private List<Integer> mIcons;
        private SparseArray<List<String>> mSubItemNames;

        public ExpandableListAdapter(List<String> mItemNames,
                List<Integer> mIcons, SparseArray<List<String>> mSubItemNames) {
            super();
            this.mItemNames = mItemNames;
            this.mIcons = mIcons;
            this.mSubItemNames = mSubItemNames;
        }

        public ExpandableListAdapter(List<String> mItemNames,
                SparseArray<List<String>> mSubItemNames) {
            super();
            this.mItemNames = mItemNames;
            this.mSubItemNames = mSubItemNames;
        }

        public void addAll(List<String> mItemNames, List<Integer> mIcons,
                SparseArray<List<String>> mSubItemNames) {
            if (mIcons == null)
                return;
            this.addAll(mItemNames, mSubItemNames);
            this.mIcons.addAll(mIcons);
        }

        public void addAll(List<String> mItemNames,
                SparseArray<List<String>> mSubItemNames) {
            if (mItemNames == null || mSubItemNames == null)
                return;
            this.mItemNames.addAll(mItemNames);
            for (int i = 0; i < mSubItemNames.size(); i++) {
                int k = mSubItemNames.keyAt(i);
                List<String> o = mSubItemNames.get(k);
                this.mSubItemNames.put(k, o);
            }
        }

        /**
         * 获取一级列表数据
         * 
         * @return
         */
        public List<Map<String, Object>> getList1_Data() {
            List<Map<String, Object>> data1 = new ArrayList<Map<String, Object>>();
            int nameCounts = mItemNames == null ? -1 : mItemNames.size();
            int iconCounts = mIcons == null ? -1 : mItemNames.size();
            int itemCounts = nameCounts > iconCounts ? nameCounts : iconCounts;
            for (int i = 0; i < itemCounts; i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                if (i < nameCounts) {
                    map.put(K_ITEM_NAME, mItemNames.get(i));
                } else {
                    map.put(K_ITEM_NAME, null);
                }
                if (i < iconCounts) {
                    map.put(K_ITEM_ICON, mIcons.get(i));
                } else {
                    map.put(K_ITEM_ICON, null);
                }
                if (mSubItemNames.get(i) == null
                        || mSubItemNames.get(i).size() == 0) {
                    map.put(K_ITEM_FLAG, null);
                } else {
                    map.put(K_ITEM_FLAG, R.drawable.wl_ic_arrow_right_small);
                }
                data1.add(map);
            }
            return data1;
        }

        /**
         * 获取二级列表数据
         * 
         * @param pos
         *            对应的一级标题位置
         * @return
         */
        public List<Map<String, Object>> getList2_Data(int pos) {
            List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
            List<String> l = mSubItemNames == null ? null : mSubItemNames
                    .get(pos);
            if (l == null)
                return data;
            for (int i = 0; i < l.size(); i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put(K_ITEM_NAME, l.get(i));
                data.add(map);
            }
            return data;
        }

        public void clearAll() {
            if (mItemNames != null)
                mItemNames.clear();
            if (mSubItemNames != null)
                mSubItemNames.clear();
            if (mIcons != null)
                mIcons.clear();
        }

    }

}
